package cn.cs.controller;

import cn.cs.client.RestClientUserClient;
import cn.cs.common.DateUtil;
import cn.cs.common.Dto;
import cn.cs.common.DtoUtil;
import cn.cs.common.JPushUtil;
import cn.cs.pojo.AppOrder;
import cn.cs.pojo.AppOrderConcelcause;
import cn.cs.pojo.ClientUser;
import cn.cs.service.AppOrderService;
import cn.cs.service.FaultTypeService;
import cn.cs.service.RepairOrderService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping(value = "/appOrder")
public class AppOrderController {
    @Autowired
    private AppOrderService service;

    @Resource
    private FaultTypeService faultTypeService;

    @Resource
    private RepairOrderService repairOrderService;

    @Resource
    private RestClientUserClient clientUserClient;


    /****
     * 发送抢预约单消息
     * @param appId 预定单id
     * @param
     * @return
     */
    @RequestMapping("/sendQdGoodsMessage")
    @ResponseBody
    public Dto sendQgGoodsMessage(@RequestParam String appId, HttpServletRequest request, HttpServletResponse response){
        Dto dto=null;
        try {
            String token = request.getHeader("token");
            response.setHeader("Access-Control-Allow-Origin", "*");
            dto=service.sendAppOrderMessage(appId, request);
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("抢单失败","0002");
        }
        return dto;
    }

    /****
     * 查询预约单信息
     * appId 预定单id
     * @param
     * @return
     */
    @RequestMapping("/getAppOrdersInfo")
    @ResponseBody
    public Dto getAppOrdersInfo( HttpServletRequest request, HttpServletResponse response){
        Dto dto=null;
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            dto=service.getAppOrdersInfo(request);
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("抢单失败","0002");
        }
        return dto;
    }

    /****
     *电器厂添加预约日期和时间
     * appId 预定单id
     * @param
     * @return
     */
    @RequestMapping("/dqcUpdateOrderTime")
    @ResponseBody
    public Dto dqcUpdateOrderTime( HttpServletRequest request, HttpServletResponse response){
        Dto dto=null;
        try {
            String token = request.getHeader("token");
            response.setHeader("Access-Control-Allow-Origin", "*");
            dto=service.dqcUpdateOrderTime(request);
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("抢单失败","0002");
        }
        return dto;
    }

    /****
     * 查询预约单信息
     * appId 预定单id
     * @param
     * @return
     */
    @RequestMapping("/getAppOrderInfo")
    @ResponseBody
    public Dto getAppOrderInfo(@RequestParam String appOrderId, HttpServletRequest request, HttpServletResponse response){
        Dto dto=null;
        try {
            String token = request.getHeader("token");
            response.setHeader("Access-Control-Allow-Origin", "*");
            dto=service.getAppOrderInfo(appOrderId,request);
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("抢单失败","0002");
        }
        return dto;
    }


    /****
     * 更改预约单状态
     * @param appId 预定单id
     * @param state 预约单状态
     * @return
     */
//    @RequestMapping("/updateAppOrderState")
//    @ResponseBody
//    public Dto updateAppOrderState(String appId,String state, HttpServletRequest request, HttpServletResponse response){
//        Dto dto=null;
//        try {
//            String token = request.getHeader("token");
//            response.setHeader("Access-Control-Allow-Origin", "*");
//            dto=service.updateAppOrderState(appId,state,token);
//        }catch (Exception e){
//            e.printStackTrace();
//            return DtoUtil.returnFail("更改失败","0002");
//        }
//        return dto;
//    }


    /****
     * 维修工拒绝指派给自己的预约单
     * @param
     * @return
     */
    @RequestMapping("/refuseAppOrder")
    @ResponseBody
    public Dto refuseAppOrder( HttpServletRequest request, HttpServletResponse response){
        Dto dto=null;
        try {
            String token = request.getHeader("token");
            response.setHeader("Access-Control-Allow-Origin", "*");
            dto=service.refuseAppOrder(request);
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("更改失败","0002");
        }
        return dto;
    }


    /**
     * 预约维修下单接口
     * */
    @RequestMapping(value = "/wxApi/registerAppOrder")
    @ResponseBody
    @Transactional
    public Dto registerAppOrder(HttpServletRequest request)throws Exception{
        return service.registerAppOrder(request);
    }

    /**
     * 判断能否下单给私人维修工
     * */
    @RequestMapping(value = "/wxApi/privateWorker")
    @ResponseBody
    public Dto privateWorker(HttpServletRequest request)throws Exception{
        return service.privateWorker(request);
    }


    /**
     * 取消订单选项接口
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/getConcelcause")
    @ResponseBody
    public Dto<AppOrderConcelcause> getConcelcause() throws Exception {
        List<AppOrderConcelcause> list=faultTypeService.getConcelcause();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        for(AppOrderConcelcause a:list){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", a.getId());
            map.put("concelCause", a.getConcelCause());
            map.put("show", false);
            mapList.add(map);
        }
        return DtoUtil.returnSuccess("获取成功",mapList);
    }

    /**
     * 取消预约订单（如果有订单，也取消）
     * @param appOrderId
     * @param cancel_reason
     * @param cancel_remark
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/cancelAppOrder")
    @ResponseBody
    @Transactional
    public Dto cancelAppOrder(String appOrderId, String cancel_reason, String cancel_remark) throws Exception {
        AppOrder order = service.getAppOrderById(appOrderId);
        String order_state = order.getOrder_state();
        if("0".equals(order_state) || "1".equals(order_state)){
            if("2".equals(order.getUser_type())){ //电器厂，取消订单，没有预约时间直接取消。
                AppOrder appOrder = new AppOrder();
                appOrder.setId(appOrderId);
                appOrder.setCancel_reason(cancel_reason);
                appOrder.setCancel_remark(cancel_remark);
                appOrder.setOrderState("6");
                service.modifyAppOrder(appOrder);

                //根据预约的Id，修改订单状态
                repairOrderService.updateOrderStatusByAppId("5", appOrderId);
                return DtoUtil.returnSuccess("取消订单成功");
            }
            String order_date = order.getOrder_date();
            String order_time = String.format("%02d", Integer.valueOf(order.getOrder_time().replace(" ", "").split(":")[0]));
            String date = order_date + " " + order_time + ":00:00";
            Double time = DateUtil.getMinuteOfTwoDate(new Date(), DateUtil.parse(date, "yyyy-MM-dd HH:mm:ss"));
            if(time >= 2 * 60 * 60){
                AppOrder appOrder = new AppOrder();
                appOrder.setId(appOrderId);
                appOrder.setCancel_reason(cancel_reason);
                appOrder.setCancel_remark(cancel_remark);
                appOrder.setOrderState("6");
                service.modifyAppOrder(appOrder);

                //根据预约的Id，修改订单状态
                repairOrderService.updateOrderStatusByAppId("5", appOrderId);
                return DtoUtil.returnSuccess("取消订单成功");
            }else if(time < 0){
                return DtoUtil.returnFail("超过预约时间，无法取消预约单", "002");
            }else{
                return DtoUtil.returnFail("距离预约时间不到2小时，无法取消预约单", "001");
            }
        }
        return DtoUtil.returnFail("预约单无法取消，请刷新后查看预约单信息", "003");

    }



    /**
     * 获取预约单详情
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/getAppOrderByAppOrderId")
    @ResponseBody
    public Dto getAppOrderByAppOrderId(String id)throws Exception{
        return DtoUtil.returnSuccess("获取预约订单详情", service.getAppOrderByAppOrderId(id));
    }


    /**
     * 用户确认收到配件 并预约维修师傅上门时间
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/confirmationProduct")
    @ResponseBody
    public Dto confirmationProduct(String id, String subscribe_date, String subscribe_time) throws Exception {
        AppOrder appOrder = new AppOrder();
        appOrder.setId(id);
        appOrder.setSubscribeTime(subscribe_time);

        appOrder.setSubscribeDate(subscribe_date);
        //预约日期  -- 转变为时间
        appOrder.setConfirmationProduct("1");
        Map<String, Object>  map = service.getRepUserIdByAppOrderId(id);
        String rep_user_id = map.get("rep_user_id").toString();

        // 发送极光推送给维修工
        String[] strSelect = new String[1];
        Map<String, String> cmap = new HashMap<String, String>();
        Map<String, String> valMap = new HashMap<String, String>();
        valMap.put("id", map.get("id").toString());
        valMap.put("user_phone", map.get("user_phone").toString());
        valMap.put("user_address", map.get("user_address").toString());
        valMap.put("subscribe_date", appOrder.getSubscribeDate());
        valMap.put("subscribe_time", subscribe_time);
        cmap.put("accessoriesArrived", JSONObject.toJSONString(valMap));
        strSelect[0] = rep_user_id;
        Object obj = JPushUtil.testSendPush(strSelect, "您的服务单配件已到货，客户和您预约了新的日期，请查看。", cmap);
        System.out.println(obj);

        return DtoUtil.returnSuccess("操作成功",service.modifyAppOrder(appOrder));
    }


    /**
     * 预约维修接口 -- 电器厂pc预约下单
     * */
    @RequestMapping(value = "/dqcApi/subscribeAppOrder")
    @ResponseBody
    @Transactional
    public Dto subscribeAppOrder(HttpServletRequest request)throws Exception{
        return service.registerAppOrder(request);
    }


    /**
     * 电器厂pc -- 跟踪订单信息
     * 超时未接订单  --  传值 overtime = 1
     *
     */
    @RequestMapping("/dqcApi/getRepairOrderByUserId")
    @ResponseBody
    public Dto getRepairOrderByUserId(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = request.getParameter("userId");//用户ID
        int pageNumber = Integer.valueOf(request.getParameter("pageNumber"));//起始页码
        int pageSize = Integer.valueOf(request.getParameter("pageSize"));//每页多少条
        String userType = "2";//用户类型 0个人用户 1企业用户 2电器厂家用户
        String isProtect = request.getParameter("isProtect");//是否质保（0否1是）
        String isRepair = request.getParameter("isRepair");//是否维修（0否1是）
        String orderState = request.getParameter("orderState");//预约单状态 0未接单 1已接单 2已检测 3已支付 4已评价 5已取消
        String overtime = request.getParameter("overtime");//是否超时未接单 1是
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userType", userType);
        map.put("isProtect", isProtect);
        map.put("isRepair", isRepair);
        map.put("orderState", orderState);
        map.put("userId", userId);
        long currentTime = System.currentTimeMillis() - 30 * 60 * 1000;
        Date date = new Date(currentTime);
        if("1".equals(overtime)){
            map.put("overtime", "1");
            map.put("createTime", DateUtil.format(date, "yyyy-MM-dd HH;mm:ss"));
            map.put("orderState", "0");
        }
        ClientUser clientUser = clientUserClient.getClientUserById(userId);
        String userPid = clientUser.getUserPid();
        map.put("userPid", userPid);
        //根据用户ID，获取用户的订单信息
        return DtoUtil.returnSuccess("查询成功", service.queryRepairOrderPageByMap(map, pageNumber, pageSize));
    }


    /**
     * 电器厂pc -- 修改一口价
     * */
    @RequestMapping(value = "/dqcApi/updateFixedPrice")
    @ResponseBody
    @Transactional
    public Dto updateFixedPrice(HttpServletRequest request)throws Exception{
        return service.updateFixedPrice(request);
    }

    /**
     * 修改一口价 -- wx
     * */
    @RequestMapping(value = "/wxApi/updateFixedPriceWX")
    @ResponseBody
    @Transactional
    public Dto updateFixedPriceWX(HttpServletRequest request)throws Exception{
        return service.updateFixedPrice(request);
    }


    /**
     * 获取物流公司信息
     * */
    @RequestMapping(value = "/p/getCourierServices")
    @ResponseBody
    @Transactional
    public Dto getCourierServices()throws Exception{
        return DtoUtil.returnDataSuccess(service.getCourierServices());
    }

    /**
     * 保存物流单号
     * */
    @RequestMapping(value = "/p/saveCourierServices")
    @ResponseBody
    @Transactional
    public Dto saveCourierServices(String orderId, String courierCompany, String courierNumber)throws Exception{
        int i = service.saveCourierServices(courierCompany, courierNumber, orderId);
        if(i > 0){
            return DtoUtil.returnSuccess("操作成功");
        }
        return DtoUtil.returnFail("操作失败，请重试！", "001");

    }

    /**
     * 获取物流信息
     * @param com
     * @param no
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wxApi/getLogisticsInformation")
    @ResponseBody
    public Dto getLogisticsInformation(String com, String no)throws Exception{
        String result = null;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet("http://v.juhe.cn/exp/index?com="+com+"&no="+no+"&key=9a4090e5886ecd9fe24c1926053d315a");

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return DtoUtil.returnSuccess("操作成功", JSON.parseObject(result, new TypeReference<Map<String, Object>>(){}));
    }

}
